<?php
class Login_Controller extends Base_Controller {

	/**
	 * Manipula o xml utilizado para descrever a tela
	 * Handles the xml used to describe the interface
	 * @var GladeXML
	 */
	private $objGlade;
	
	/**
	 * Objeto janela recuperado do XML do Glade
	 * Window object recovered from Glade XML
	 * @var GtkWindow
	 */
	private $objWindow;

	/**
	 * Array de conexões armazendas
	 * Stored connections array
	 * @var unknown_type
	 */
	private $objStoredConnections;
	
	/**
	 * Conecta os sinais e define o titulo da janela
	 * Connect the signals and defines the title of the window
	 */
	public function __construct() {
		$this->objGlade = new GladeXML(dirname(__FILE__) . '/resources/xml/login.glade');
		$this->objGlade->signal_autoconnect_instance($this);
		$this->objWindow = $this->objGlade->get_widget('loginWindow');
		$this->objWindow->set_title(ts::config('title.main'));
		
		$this->initializeInterface();
	}
	
	/**
	 * Iniciliza todos os itens de interface da janela
	 * Initializes all interface items in the window
	 */
	private function initializeInterface() {
		$txtHost = $this->objGlade->get_widget('txtHost');
		$txtHost->grab_focus();
		
		$this->loadStoredConnections();
	}
	
	/**
	 * Carrega as conexões armazenadas no arquivo de configuração
	 * Loads all connections stored 
	 */
	private function loadStoredConnections() {
		if( ! file_exists(ts::config('path.main') . '/resources/connection.json')) {
			$objFile = fopen(ts::config('path.main') . '/resources/connection.json', 'w');
			fclose($objFile);
			$this->objStoredConnections = new stdClass;
		}
		else {
			$this->objStoredConnections = json_decode(file_get_contents(ts::config('path.main') . '/resources/connection.json'));
			if(! isset($this->objStoredConnections))
				$this->objStoredConnections = new stdClass;
		}
		
		$this->renderConnectionsCombo(true);
	}
	
	private function renderConnectionsCombo($boolFirstTime = false) {
		$list = new GtkListStore(GObject::TYPE_STRING);
		if(count($this->objStoredConnections) > 0) {
			foreach($this->objStoredConnections as $strKey => $objConnection)
				$list->append(array($strKey));
		}

		$cbStoredConnections = $this->objGlade->get_widget('cbStoredConnections');
		$cbStoredConnections->set_model($list);
//		var_dump($list->);

		if($boolFirstTime == true) {
			$cellRender = new GtkCellRendererText;
			$cbStoredConnections->pack_start($cellRender);
			$cbStoredConnections->set_attributes($cellRender, 'text', 0);
		}
	}
	
	public function cbStoredConnections_changed(GtkComboBox $cbStoredConnections) {
		$strActive = $cbStoredConnections->get_active_text();
		$objSelectedItem = $this->objStoredConnections->$strActive;
		$this->objGlade->get_widget('txtHost')->set_text($objSelectedItem->strHost);
		$this->objGlade->get_widget('txtUserName')->set_text($objSelectedItem->strUserName);
		$this->objGlade->get_widget('txtPassword')->set_text(base64_decode(base64_decode(base64_decode($objSelectedItem->strPassword))));
		$this->objGlade->get_widget('txtPort')->set_text($objSelectedItem->intPort);
		$this->objGlade->get_widget('txtDatabases')->set_text($objSelectedItem->strDatabases);
		$this->objGlade->get_widget('chkCompressedProtocol')->set_active(($objSelectedItem->boolCompressedProtocol == true));
	}
	
	public function btnNew_clicked() {
		$dialogConnectionName = new ConnectionName_Controller($this->objWindow);
		if($dialogConnectionName->getExitCode() == 0) {
			$strConnectionName = $dialogConnectionName->getConnectionName();
			
			if(! isset($this->objStoredConnections->$strConnectionName)) {
				$this->objStoredConnections->$strConnectionName = new stdClass;
				$this->objStoredConnections->$strConnectionName->strHost = "";
				$this->objStoredConnections->$strConnectionName->strUserName = "";
				$this->objStoredConnections->$strConnectionName->strPassword = "";
				$this->objStoredConnections->$strConnectionName->intPort = "3306";
				$this->objStoredConnections->$strConnectionName->strDataBases = "";
				$this->objStoredConnections->$strConnectionName->boolCompressedProtocol = "";
				$this->renderConnectionsCombo();
				
				$cbStoredConnections = $this->objGlade->get_widget('cbStoredConnections');
				$cbStoredConnections->set_active(count($this->objStoredConnections));
			}
			else {
				$objDialogInformation = new GtkMessageDialog($this->objWindow, 0, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_OK, '');
			 	$objDialogInformation->set_markup("<span color=\"#FF0000\">Connection alredy exists!</span>");
				$objDialogInformation->run();
				$objDialogInformation->destroy();
			}
		}
		else
			$strConnectionName = '';
	}

	public function btnSave_clicked() {
		$objCBStoredConnections = $this->objGlade->get_widget('cbStoredConnections');
		$strConnectionName = $objCBStoredConnections->get_active_text();
		$this->objStoredConnections->$strConnectionName = $this->getConnectionInformation();
		
		$objFile = fopen(ts::config('path.main') . '/resources/connection.json', 'w');
		fwrite($objFile, json_encode($this->objStoredConnections));
		fclose($objFile);
	}
	
	public function btnRename_clicked() {
		
	}
	
	public function btnDelete_clicked() {
		
	}
	
	public function rdbSessionUser_toggled() {
		$txtTimeout = $this->objGlade->get_widget('txtTimeout');
		if($this->objGlade->get_widget('rdbSessionUser')->get_active() === true) {
			$txtTimeout->grab_focus();
			$txtTimeout->set_editable(true);
			$txtTimeout->select_region(0, strlen($txtTimeout->get_text()));
		}
		else {
			$txtTimeout->set_editable(false);
			$txtTimeout->grab_remove();
		}
	}
	
	
	public function txtTimeout_key_press(GtkWidget $widget, GdkEvent $event) {
		return false;
	}
	
	public function btnConnect_clicked() {
		
	}
	
	/**
	 * Fecha a janela
	 * Closes the window
	 */
	public function btnCancel_clicked() {
		$this->objWindow->destroy();
	}
	
	/**
	 * Testa a conexão e exibe uma mensagem com o resultado
	 * Tests the connection and show message with the connection result
	 */
	public function btnTestConnection_clicked() {
		$objConnectionData = $this->getConnectionInformation();
		$objConnectionResult = DataBase_Model::testConnection($objConnectionData->strHost, $objConnectionData->strUserName, $objConnectionData->strPassword, null, $objConnectionData->intPort);
		if($objConnectionResult->intErrorNumber != 0) {
		 	$objDialogInformation = new GtkMessageDialog($this->objWindow, 0, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_OK, '');
		 	$objDialogInformation->set_markup("Erro de conexão:\n\n<b>Código: </b>" . $objConnectionResult->intErrorNumber . "\n<b>Mensagem: </b>" . $objConnectionResult->strErrorMessage);
			$objDialogInformation->run();
			$objDialogInformation->destroy();
		}
		else {
			$objDialogInformation = new GtkMessageDialog($this->objWindow, 0, Gtk::MESSAGE_INFO, Gtk::BUTTONS_OK, 'Conexão bem sucedida!');
			$objDialogInformation->run();
			$objDialogInformation->destroy();
		} 
	}
	
	/**
	 * Recupera os dados dos campos da tela
	 * Recovers the data of the fields on the interface
	 */
	private function getConnectionInformation() {
		$objConnectionData = new stdClass;
		$objConnectionData->strHost = ($this->objGlade->get_widget('txtHost')->get_text() == 'localhost' ? '127.0.0.1' : $this->objGlade->get_widget('txtHost')->get_text());
		$objConnectionData->strUserName = $this->objGlade->get_widget('txtUserName')->get_text();
		$objConnectionData->strPassword = base64_encode(base64_encode(base64_encode(($this->objGlade->get_widget('txtPassword')->get_text() == '' ? null : $this->objGlade->get_widget('txtPassword')->get_text()))));
		$objConnectionData->intPort = ($this->objGlade->get_widget('txtPort')->get_text() == '' ? null : $this->objGlade->get_widget('txtPort')->get_text());
		$objConnectionData->strDataBases = $this->objGlade->get_widget('txtDatabases')->get_text();
		$objConnectionData->boolCompressedProtocol = $this->objGlade->get_widget('chkCompressedProtocol')->get_active();
//		$objConnectionData->intSessionIdleTimeout = ;

		return $objConnectionData;
	}
}
?>